import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router  from '@/router'
const request = axios.create({
  baseURL: '/api',
  timeout: 10000
})

request.interceptors.request.use(config => {
  console.log('请求拦截器:', config)
  const token = store.getters.token
  if(token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, error => Promise.reject(error))

request.interceptors.response.use( response => {

  // axios默认包裹了data
  // 判断是不是Blob
  if (response.data instanceof Blob) return response.data // 返回了Blob对象

  
  const { data, message, success } = response.data
  if(success){
    return data
  } else {
    Message({ type: 'error', message })
    return Promise.reject(message)
  }
}, async error => { 
  console.dir(error)
  if (error.response && error.response.status === 401) {
    Message({ type: 'warning', message: 'token超时了' })
    // 说明token超时了
    await store.dispatch('user/logout') // 调用action 退出登录
    //  主动跳到登录页
    router.push('/login') // 跳转到登录页
    return Promise.reject(error)
  }
  Message({ type: 'error', message: error.message })
  return Promise.reject(error)})

export default request